<?php


namespace app\common\business;


use app\common\lib\Arr;

use think\facade\Cache;
use think\Exception;

class Goods extends BusBass
{
    public $model = Null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\Goods();
    }

    //首页分页 获取数据
    public function getLists($data, $num = 5)
    {
        $likeKeys = [];
        if (!empty($data)) {
            $likeKeys = array_keys($data); //获得键名

        }
        try {
            $list = $this->model->getLists($likeKeys, $data, $num);
            $result = $list->toArray();
        } catch (\Exception $e) {

            $result = Arr::getPaginateDefaultData();
        }
        return $result;
    }


    //新增商品逻辑
    public function insertData($data)
    {
        //启动事务
        $this->model->startTrans();

        try {
            $goodsId = $this->add($data);
            if (!$goodsId) {
                return $goodsId;
            }
            //执行数据 插入到 sku表中
            //如果是统一规格
            if ($data['goods_specs_type'] == 1) {
                $goodsSkuData = [
                    "goods_id" => $goodsId
                ];
                return true;
                //如果是多规格
            } elseif ($data['goods_specs_type'] == 2) {
                $goodsSkuBisobj = new GoodsSku();
                $data['goods_id'] = $goodsId;  //赋值 插入信息的主键ID
                //多规格新增逻辑
                $res = $goodsSkuBisobj->saveAll($data);

                //如果多规格不为空
                if (!empty($res)) {
                    //总库存 找出多规格库存的值 相加
                    $stock = array_sum(array_column($res, "stock"));
                    //更新基础信息库
                    $goodsUpdateData = [
                        "price" => $res[0]['price'],
                        "cost_price" => $res[0]['cost_price'],
                        "stock" => $stock,
                        "sku_id" => $res[0]['id'],
                    ];
                    //更新表
                    $goodsRes = $this->model->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw  new Exception("insertData:goods主表更新失败");
                    }
                } else {
                    throw  new Exception("sku表更新失败");
                }
            }
            //事务提交
            $this->model->commit();
            return true;
        } catch (\Exception $e) {
            // 日志
            //事务回滚
            $this->model->rollback();
            return false;
        }
        return true;
    }

    //根据ID获取这条记录
    public function getById($id)
    {
        $result = $this->model->find($id);
        if (empty($result)) {
            return [];
        }

        $result = $result->toArray();
        return $result;
    }

    //排序逻辑
    public function listorder($id, $listorder)
    {
        //查询 id这条数据是否存在
        $res = $this->getById($id);

        if (!$res) {
            throw new Exception("不存在该条记录");
        }
        $data = [
            'listorder' => $listorder
        ];
        //更新排序
        try {
            $res = $this->model->updateById($id, $data);
        } catch (\Exception $e) {
            return false;
        }
        return $res;
    }


    //更新状态的逻辑
    public function status($id, $status)
    {
        $res = $this->getById($id);
        if (!$res) {
            throw new Exception('不存在该条记录');
        }
        if ($res['status'] == $status) {
            throw new Exception('状态修改前和修改后一样没有意义');
        }
        $data = [
            "status" => intval($status),
        ];

        try {
            $res = $this->model->updateById($id, $data);
        } catch (\Exception $e) {
            return new Exception($e->getMessage());
        }
        return $res;
    }

    //是否推荐逻辑
    public function isIndexRecommend($id, $index)
    {
        $res = $this->getById($id);
        if (!$res) {
            throw new Exception('不存在该条记录');
        }

        $data = [
            "is_index_recommend" => intval($index),
        ];
        try {
            $res = $this->model->updateById($id, $data);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        return $res;

    }

    //获取轮播图 逻辑
    public function getRotationChart()
    {
        $data = [
            "is_index_recommend" => 1,

        ];
        //选择获取的字段 并改键名
        $field = "sku_id as id,title,big_image as image";
        //获取轮播图 逻辑
        try {
            $result = $this->model->getNormalGoodsByCondition($data, $field, 5);
        } catch (\Exception $e) {
            return [];
        }
        return $result->toArray();
    }


    //获取首页栏目推荐的商品
    public function cagegoryGoodsRecommend($categoryIds)
    {
        if (!$categoryIds) {
            return [];
        }

        //栏目获取  in category 表里的pid
        $result = [];

        //根据categoryid 获取数据
        $field = "id as category_id,name,pid,icon";
        $categoryObj = new \app\common\model\mysql\Category();
        $categoryOne = $categoryObj->getNormalCategoryId("id", $categoryIds, $field);
        $categoryOne = $categoryOne->toArray();
        //根据categoryid 获取上级分类
        $category = $categoryObj->getNormalCategoryId("pid", $categoryIds, $field);
        $category = $category->toArray();

        $cass = [];
        foreach ($categoryOne as $k => $v) {
            $cass = $v;
            foreach ($category as $k1 => $v1) {
                if ($v1['pid'] == $v['category_id']) {
                    $cass['list'][$k1] = $v1;
                }
            }
            $result[$k]['categorys'] = $cass;

        }


        foreach ($categoryIds as $key => $categoryId) {
            $result[$key]["goods"] = $this->getNormalGoodsFindInSetCategoryId($categoryId);
        }

        return $result;
    }


    // 根据分类id 获取商品表 sku id 和商品数据
    public function getNormalGoodsFindInSetCategoryId($categoryId)
    {

        //选择获取的字段 并改键名
        $field = "sku_id as id,title,price,recommend_image as image";

        try {
            $result = $this->model->getNormalGoodsFindInSetCategoryId($categoryId, $field);
        } catch (\Exception $e) {
            return [];
        }

        return $result->toArray();
    }


    //商品列表页
    public function getNormalLists($data, $num = 5, $order)
    {
        try {
            $field = "sku_id as id,title,recommend_image as image,price";
            //根据category_id 查询goods表里category_path_id 获取商品信息
            $list = $this->model->getNormalLists($data, $num, $field, $order);
            $res = $list->toArray();
            //组装分页格式
            $result = [
                "total_page_num" => isset($res['last_page']) ? $res['last_page'] : 0,
                "count" => isset($res['total']) ? $res['total'] : 0,
                "page" => isset($res['current_page']) ? $res['current_page'] : 0,
                "page_size" => $num,
                "list" => isset($res['data']) ? $res['data'] : 0,
            ];

        } catch (\Exception $e) {
            $result = [];
        }

        return $result;
    }

    //搜索逻辑
    public function getSearchLists($data, $num = 5, $order)
    {

        $likeKeys = [];
        if (!empty($data)) {
            $likeKeys = array_keys($data); //获得键名
        }

        try {
            $field = "sku_id as id,title,recommend_image as image,price";
            $list = $this->model->getSearchLists($likeKeys, $data, $num, $order, $field);
            $res = $list->toArray();

            //组装分页格式
            $result = [
                "total_page_num" => isset($res['last_page']) ? $res['last_page'] : 0,
                "count" => isset($res['total']) ? $res['total'] : 0,
                "page" => isset($res['current_page']) ? $res['current_page'] : 0,
                "page_size" => $num,
                "list" => isset($res['data']) ? $res['data'] : 0,
            ];

            //组装分页格式
        } catch (\Exception $e) {

            $result = [];
        }
        return $result;

    }

    //通过sku_Id获取 商品详情
    public function getGoodsDetailBySkuId($skuId)
    {
        //通过sku_id到sku表查到 goods_id 在goods表里查到数据
        $skuBisObj = new GoodsSku();
        $goodsSku = $skuBisObj->getNormalSkuAndGoods($skuId);
        if (!$goodsSku) {
            return [];
        }

        if (empty($goodsSku['goods'])) {
            return [];
        }
        $goods = $goodsSku['goods'];

        //通过goods_id 在sku表里查询sku数据
        $skus = $skuBisObj->getSkusByGoodsId($goods['id']);
        if (!$skus) {
            return [];
        }

        //传递$flagValue
        $flagValue = "";
        foreach ($skus as $sv) {
            if ($sv['id'] == $skuId) {
                $flagValue = $sv["specs_value_id"];
            }
        }
        $gids = [];
        $gids = array_column($skus, "id", "specs_value_id");

        //判断是多规格还是统一规格
        if ($goods["goods_specs_type"] == 1) {
            $sku = [];
        } else {
            //sku数据
            $sku = (new SpecsValue())->dealGoodsSkus($gids, $flagValue);
        }

        $result = [
            "title" => $goods['title'],
            "price" => $goodsSku['price'],
            "cost_price" => $goodsSku['cost_price'],
            "sales_count" => 0,
            "stock" => $goodsSku['stock'],
            "gids" => $gids,
            "image" => $goods['carousel_image'],
            "sku" => $sku,
            "detail" => [
                "d1" => [
                    "商品编码" => $goodsSku['id'],
                    "上架时间" => $goods['create_time'],
                ],
                "d2" => preg_replace('/(<img.+?src=")(.*?)/', '$1' . request()->domain() . '$2', $goods['description']),
            ],
        ];

        //记录数据到redis 作为商品pv统计 按商品id统计
        Cache::inc("mall_pv" . $goods['id']);
        return $result;
    }
}